package org.jeecg.modules.nikeProject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.nikeProject.entity.SportsPersonalInfo;
import org.jeecg.modules.nikeProject.entity.SportsProject;
import org.jeecg.modules.nikeProject.entity.SportsQualificationDoc;
import org.jeecg.modules.nikeProject.mapper.SportsPersonalInfoMapper;
import org.jeecg.modules.nikeProject.mapper.SportsProjectMapper;
import org.jeecg.modules.nikeProject.mapper.SportsQualificationDocMapper;
import org.jeecg.modules.nikeProject.service.ISportsQualificationDocService;
import org.jeecg.modules.system.mapper.SysDictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 案例评审-案例资质文件
 * @Author: jeecg-boot
 * @Date:   2024-12-05
 * @Version: V1.0
 */
@Slf4j
@Service
public class SportsQualificationDocServiceImpl extends ServiceImpl<SportsQualificationDocMapper, SportsQualificationDoc> implements ISportsQualificationDocService {

    @Autowired
    private SportsQualificationDocMapper qualificationDocMapper;
    @Autowired
    private SysDictMapper sysDictMapper;
    @Autowired
    private SportsProjectMapper projectMapper;
    @Autowired
    private SportsProjectMapper sportsProjectMapper;
    @Autowired
    private SportsPersonalInfoMapper sportsPersonalInfoMapper;

    @Override
    @Transactional
    public Result<?> add(SportsQualificationDoc sportsQualificationDoc, String username) {
        if ("".equals(sportsQualificationDoc.getFileUrl()) || null == sportsQualificationDoc.getFileUrl()){
            return Result.OK("未填写相关信息");
        }

        String projectId = sportsQualificationDoc.getProjectId();
        if (null == projectId || "".equals(projectId)) {
            return Result.error("未查找到案例信息，请联系管理员处理！");
        }
        SportsProject sportsProject = projectMapper.selectById(projectId);
//        if (CommonConstant.PROJECT_STEP_FINISH.equals(sportsProject.getProjectStep())){
//            return Result.error("案例已提交，不允许编辑!");
//        }
        //查询是否存在案例资质文件
        SportsQualificationDoc qualificationDoc = getSportsQualificationDocByProjectId(projectId);
        if (null != qualificationDoc) {
            qualificationDoc.setUpdateBy(username);
            qualificationDoc.setUpdateTime(new Date());
            qualificationDoc.setIzActive("1");
            qualificationDocMapper.updateById(qualificationDoc);
        } else {
            if (!CommonConstant.PROJECT_STEP_FINISH.equals(sportsProject)){
                sportsProject.setProjectStep(CommonConstant.PROJECT_STEP_UPLOAD_QUALIFICATION_DOC);
                sportsProject.setUpdateTime(new Date());
                sportsProject.setUpdateBy(username);
                projectMapper.updateById(sportsProject);
            }
        }
        sportsQualificationDoc.setCreateBy(username);
        sportsQualificationDoc.setCreateTime(new Date());
        int i = qualificationDocMapper.insert(sportsQualificationDoc);
        if (i == 0) {
            return Result.error("添加失败", projectId);
        }
        return Result.OK("添加成功！");
    }

    /**
     * 下载资质文件
     * 1.根据案例编号查询当前案例的填报人角色，填报人基本信息
     * 2.写入数据到模板
     * 3.上传写好的数据至OSS上 文件名称以案例编号+资质文件命名
     * 4.返回oss地址
     * @param projectId
     * @return
     */
    @Override
    public Result<?> downloadDoc(String projectId) throws FileNotFoundException {
        String tempFilePath = "";
        // 创建一个HashMap来存储要替换的数据
        Map<String, String> paramsMap = new HashMap<>();
        SportsProject sportsProject = sportsProjectMapper.selectById(projectId);
        if (null == sportsProject){
            return Result.error("无此案例数据！请联系管理员！");
        }
        SportsPersonalInfo sportsPersonalInfo = sportsPersonalInfoMapper.selectByProjectId(projectId);
        if (null != sportsPersonalInfo){
            String address = "";
            if (null != sportsPersonalInfo.getSchoolAddress() &&  !"".equals(sportsPersonalInfo.getSchoolAddress())){
                address = sportsPersonalInfo.getSchoolAddress();
            } else if (null != sportsPersonalInfo.getAddress() &&  !"".equals(sportsPersonalInfo.getAddress())){
                address = sportsPersonalInfo.getAddress();
            } else {
                address = "请填写地址！";
            }
            paramsMap.put("address", address);
            //一线体育老师
            if (CommonConstant.ROLE_TYPE_TE.equals(sportsProject.getRoleType())){
                if (null != sportsProject.getCaseType() && !"".equals(sportsProject.getCaseType())){
                    paramsMap.put("caseTypeName", getCaseTypeName(sportsProject.getCaseType()));
                }
            }
            if (null == sportsProject.getProjectName() || "".equals(sportsProject.getProjectName())){
                paramsMap.put("projectName", "请填写案例名称！");
            } else {
                paramsMap.put("projectName", sportsProject.getProjectName());
            }
            paramsMap.put("schoolName", sportsPersonalInfo.getSchoolName());
            if (null == sportsProject.getUserName() && "".equals(sportsProject.getUserName())){
                return Result.error("案例填报人数据不能为空！");
            }
            paramsMap.put("applyName", sportsProject.getUserName());
            File filePath = getFilePath(sportsProject.getRoleType());
            try {
                tempFilePath = packageDoc(paramsMap, filePath);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error(e.getMessage());
            }
        }
        return Result.OK("success", tempFilePath);
    }

    public File getFilePath(String roleType) throws FileNotFoundException {
        File file;
        switch (roleType) {
            case CommonConstant.ROLE_TYPE_TE:
//                classPathResource = new ClassPathResource("classpath:doc/te.docx");
                file = new File("/opt/te.docx");
//                file = new File("opt\\te.docx");
                break;
            case CommonConstant.ROLE_TYPE_PA:
                file = new File("/opt/pa.docx");
//                file = new File("opt\\pa.docx");
                break;
            case CommonConstant.ROLE_TYPE_SM:
                file = new File("/opt/sm.docx");
//                file = new File("opt\\sm.docx");
                break;
            default:
                file = new File("/opt/sr.docx");
//                file = new File("opt\\sr.docx");
                break;
        }
        return file;
    }

    public String packageDoc(Map<String, String> replacements, File file) throws Exception{
        // 保存修改后的文档
        String fileName = file.getName();
        if (fileName.equals("te.docx")){
            fileName = "体育老师资质文件.docx";
        }
        if (fileName.equals("pa.docx")){
            fileName = "推广大使资质文件.docx";
        }
        if (fileName.equals("sm.docx")){
            fileName = "校长遴选资质文件.docx";
        }
        if (fileName.equals("sr.docx")){
            fileName = "教研员遴选资质文件.docx";
        }

        String filePath = "/opt/doc/" + fileName;
//        String filePath = "opt\\" + fileName;

//            InputStream is= classPathResource.getInputStream();
        InputStream inputStream = new FileInputStream(file);
        XWPFDocument doc = new XWPFDocument(inputStream);
        // 遍历文档中的所有段落，查找并替换占位符
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            replaceTextInParagraph(paragraph, replacements);
        }
        // 遍历文档中的所有表格（如果有的话）
        for (XWPFTable table : doc.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph p : cell.getParagraphs()) {
                        replaceTextInParagraph(p, replacements);
                    }
                }
            }
        }
        // 保存修改后的文档
        try (FileOutputStream out = new FileOutputStream(filePath)) {
            doc.write(out);
        }
        return "temp/" + fileName;
//        return "temp\\" + fileName;
    }

    private static void replaceTextInParagraph(XWPFParagraph paragraph, Map<String, String> replacements) {
        // 获取段落中的运行内容（Runs）并替换文本
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0); // 获取运行中的文本内容
            if (text != null) {
                for (Map.Entry<String, String> entry : replacements.entrySet()) {
//                    log.info("text == {}, replace = {}, value = {}", text, entry.getKey(), entry.getValue());
                    text = text.replace("${" + entry.getKey() + "}", entry.getValue()); // 替换文本占位符
                }
                run.setText(text, 0); // 设置新的文本内容到运行中
            }
        }
    }

    public SportsQualificationDoc getSportsQualificationDocByProjectId(String projectId){
        LambdaQueryWrapper<SportsQualificationDoc> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SportsQualificationDoc::getProjectId, projectId);
        lambdaQueryWrapper.eq(SportsQualificationDoc::getIzActive, "0");
        return qualificationDocMapper.selectOne(lambdaQueryWrapper);
    }

    public String getCaseTypeName(String caseType){
        String caseTypeName = "";
        switch (caseType) {
            case CommonConstant.CASE_TYPE_TEACH:
                caseTypeName = CommonConstant.CASE_TYPE_TEACH_NAME;
                break;
            case CommonConstant.CASE_TYPE_CULTURE:
                caseTypeName = CommonConstant.CASE_TYPE_CULTURE_NAME;
                break;
            case CommonConstant.CASE_TYPE_ACTIVITY:
                caseTypeName = CommonConstant.CASE_TYPE_ACTIVITY_NAME;
                break;
            default:
                caseTypeName = CommonConstant.CASE_TYPE_OTHER_NAME;
        }
        return caseTypeName;
    }
}
